<template>
    <div class="container">
        <div class="apps-head" >
            
            <div class="app-add " justify="center">
                {{ state.appInfo.name }}
            </div>
            <div class="app-box flex-1">
                <div class="item-box flex-1">
                    <div class="cell">
                        <span class="app-title">应用名称：</span>
                        <span class="app-text">{{ state.appInfo.name }}</span>
                    </div>
                    <div class="cell">
                        <span class="app-title">客户端类型：</span>
                        <span class="app-text">{{ state.appInfo.clientType }}</span>
                    </div>
                    <div class="cell">
                        <span class="app-title">AppId：</span>
                        <span class="app-text">{{  state.appInfo.id }}</span>
                    </div>
                </div>
                <div class="item-box flex-1">
                    <div class="cell">
                        <span class="app-title">创建时间：</span>
                        <span class="app-text">{{  new Date(state.appInfo.createDate).toLocaleString() }}</span>
                    </div>
                    <div class="cell">
                        <span class="app-title">更新时间：</span>
                        <span class="app-text">{{ new Date(state.appInfo.modifyDate).toLocaleString() }}</span>
                    </div>
                </div>
                <div class="item-box flex-1">
                    <div class="cell">
                        <span class="app-title">启用/停用：</span>
                        <span>
                            <el-switch
                                disabled
                                v-model="state.appInfo.isEnable"
                                inline-prompt
                                active-text="启用"
                                inactive-text="停用"
                                @change="switchEnable"
                            />
                        </span>
                    </div>
                    <div class="cell">
                        <span class="app-title">是否删除：</span>
                        <span>
                            <el-tag v-if="state.appInfo.isDelete" size="small" type="warning">是</el-tag>
                            <el-tag v-else size="small" type="primary">否</el-tag>
                        </span>
                    </div>
                </div>
            </div>
            
        </div>
        <div class="remarks">
            备注：<span>{{ state.appInfo.description }}</span>
        </div>
        <el-divider />
        <div>
            <el-button type="primary" @click="state.dialogFormVisible = true">上传新版本</el-button>
            <el-button type="info" @click="appUpdateStatusFun">启用/停用</el-button>
            <el-button type="danger" @click="appDelete">删除</el-button>
        </div>
        <br>
        <div>
            <el-table
                ref="multipleTableRef"
                :data="state.tableData"
                :border="true" 
                style="width: 100%"
                highlight-current-row
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column property="version" label="版本号" />
                <el-table-column property="description" label="更新内容" show-overflow-tooltip width="200" />
                <el-table-column label="状态">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status == 'Enable' " size="small" type="primary">启用</el-tag>
                        <el-tag v-else-if="scope.row.status == 'Disable'" size="small" type="warning">停用</el-tag>
                        <!-- <el-tag v-else-if="scope.row.status == 'Delete'" size="small" type="danger">删除</el-tag> -->
                    </template>
                </el-table-column>
                <el-table-column label="上传时间">
                    <template #default="scope">{{ new Date(scope.row.createDate).toLocaleString() }}</template>
                </el-table-column>
            </el-table>
            <!-- <div style="margin-top: 20px">
                <el-button @click="toggleSelection([tableData[1], tableData[2]])"
                >Toggle selection status of second and third rows</el-button
                >
                <el-button @click="toggleSelection()">Clear selection</el-button>
            </div> -->
        </div>


        <el-dialog v-model="state.dialogFormVisible" title="上传新版本" width="500" @close="dialogClose">
            <el-form ref="uploadForm" :model="state.form">
                <el-form-item label="APP包" :label-width="state.formLabelWidth">
                    <el-input
                    v-model="state.inputfile.name" disabled style="width: 240px;" placeholder="选择文件" />
                    <el-upload
                        ref="upload"
                        style="margin-left: 10px;"
                        class="upload-demo"
                        action="#"
                        :accept="state.appInfo.clientType == 'iOS' ? '.ipa' : '.apk'"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :auto-upload="false"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        :on-change="uploadChange"
                        :headers="headers"
                    >
                        <template #trigger>
                            <el-button type="primary">选择</el-button>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="版本号" :label-width="state.formLabelWidth">
                    <el-input v-model="state.form.version" autocomplete="off" maxlength="30" @input="filterInput2" />
                </el-form-item>
                <el-form-item label="更新内容" :label-width="state.formLabelWidth">
                    <el-input
                        v-model="state.form.description"
                        style="width: 240px"
                        :rows="2"
                        type="textarea"
                        placeholder=""
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                <el-button @click="dialogClose">取消</el-button>
                <el-button type="primary" @click="saveApp">
                    确定
                </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
    
</template>

<script lang="ts" setup>
import { defineComponent,reactive, ref, toRefs , watchEffect , onMounted } from 'vue'
import { ElMessage, ElMessageBox , ElLoading , genFileId , ElTable } from 'element-plus';
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { appVersionList , uploadVersion , updateVersionStatus } from '@/axios/api'

const prevAppData = history.state && history.state.data && JSON.parse(history.state.data);

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const uploadForm = ref(null);

const headers = {
    'Content-Type': 'multipart/form-data'
}

let loading:any = null;
const openLoading = function(){
  loading = ElLoading.service({
    lock: true,
    text: '加载中...'
  })
}
const closeLoading = function(){
  loading && loading.close();
}

const state = reactive({
    inputfile:{
        name:"",
        raw:{

        }
    },
    tableData:[
        // {
        //     id:"",
        //     application:"",
        //     version:"",
        //     versionCode:"",
        //     description:"",
        //     createDate:"",
        //     updateType:"",
        //     status:"",
        //     applicationId:"",
        //     multipartFile:"",
        //     appLink:""
        // }
    ],
    // appInfo:{
    //     name:prevAppData.name,
    //     clientType:prevAppData.clientType,
    //     createDate:prevAppData.createDate,
    //     modifyDate:prevAppData.modifyDate,
    //     isEnable:prevAppData.isEnable,
    //     isDelete:prevAppData.isDelete,
    //     description:prevAppData.description
    // },
    appInfo:{
        ...prevAppData,
        isEnable:prevAppData.isEnable == '1' ? true : false
    },
    
    form :{
        version: '',
        description:""
    },
    dialogFormVisible:false,
    formLabelWidth:'140px',

})

// const props = defineProps({
//     data: {
//         type: String,
//         default: ''
//     },
// })

const initTableData = function(){
    //初始化获取表格数据
    const appId =  prevAppData.id;
    appVersionList(
        {
            applicationId:appId
        }
    ).then((res:any)=>{
        state.tableData = res.data.data;
    }).catch((err:any)=>{
        console.log(err);
    })
}

onMounted(  () => {
    initTableData();
})

// 启用停用开关切换
const switchEnable = function(status:any){
    console.log(status)
    if(status){ //开启

    }else { //关闭

    }
    openLoading();
    setTimeout(()=>{
        closeLoading();
        // state.appInfo.isEnable = false;
    },1000);
}

//表格只选择一行
const handleSelectionChange = (rowData:any) => {
  if(rowData.length > 1){
      multipleTableRef.value!.clearSelection();
      multipleTableRef.value!.toggleRowSelection(rowData.pop(),true);
  }
}
const filterInput2 = function(){
  state.form.version = state.form.version.replace(/[^a-zA-Z0-9]/g, '');
}
// 上传新版本-整体逻辑
const upload = ref<UploadInstance>(); //上传按钮对象

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const submitUpload = () => {
  upload.value!.submit()
}

const dialogClose = function(){
    // uploadForm.resetFields();
    state.inputfile = {
        name:"",
        raw:{}
    };
    state.form.version = '';
    state.form.description = '';
    state.dialogFormVisible = false;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('请上传格式为jpeg/png')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片体积最大5M')
        return false
    }
    return true
}


const uploadChange = function(file:any){
    console.log(file)
    state.inputfile = file;
}
const handleStart = function(data:any){
    console.log(data + "handleStart")
}
//上传新版本保存
const saveApp = function(){
    let formData = new FormData();
    formData.append('multipartFile',state.inputfile.raw);
    formData.append('applicationId',prevAppData.id);
    formData.append('version',state.form.version);
    formData.append('description',state.form.description);
    openLoading();
    uploadVersion(
        formData,
        {
            headers:{
                ...headers,
                Accept:'*/*',
            }
        }
    ).then(res=>{
        closeLoading();
        dialogClose();
        initTableData();
    }).catch(err=>{
        closeLoading();
        ElMessage(err.message);
    })
}

// --------版本内启用停用逻辑
const appUpdateStatusFun = function(){
    const selectRows = multipleTableRef.value?.getSelectionRows();
    const rowId = selectRows[0].id;
    const rowStatus = selectRows[0].status;
    const newStatus = rowStatus == 'Enable' ? 'Disable' : 'Enable';
    updateVersionStatus(
        {
            id:rowId,
            status:newStatus
        }
    ).then(res=>{
        state.tableData.forEach((item:any)=>{
            if(item.id == rowId){
                item.status = newStatus;
            }
        });
    }).catch(err=>{
        ElMessage(err.message);
    })
}

// ----------删除逻辑
const appDelete = function(){
    const selectRows = multipleTableRef.value?.getSelectionRows();
    const rowId = selectRows[0].id;
    updateVersionStatus(
        {
            id:rowId,
            status:'Delete'
        }
    ).then(res=>{
        state.tableData = state.tableData.filter((item:any)=>{
            return item.id != rowId;
        });
    }).catch(err=>{
        ElMessage(err.message);
    })
}



// watchEffect(()=>{
//     console.log('进入监听')
//     console.log(upload.value)
//     // upload.value = {}
//     upload.value.clearFiles()
//     // state.fileList = []
// })





</script>

<style lang="scss" scoped>

//隐藏表格多选
:deep(.el-table th.el-table__cell:nth-child(1) .cell){
    visibility: hidden
}
.flex-1{
    flex: 1;
}
.container{
    .remarks{
        margin:13px;
    }
    .apps-head{
        display: flex;
    }
    .app-add{
        margin: 10px;
        width: 100px;
        height: 100px;
        border-radius: 5px;
        background-color: #eee;
        text-align: center;
        align-items: center;
        align-content: center;
        justify-items: center;
    }
    .app-box{
        display: flex;
        margin: 20px;
        margin-top: 10px;
        align-items: center;
        .item-box{
            margin-left: 10px;
        }
        .cell{
            padding: 5px;
        }
        .app-title{
            color: #666;
        }
    }
}


</style>
